﻿(function (jquery) {
    //defined variable
    var currentobj,
    _getdata = function (opts, callback) {
        jquery.ajax({
            type: "post",
            dataType: "text",
            url: opts.requestdataurl,
            cache: false,
            data: { sfbcode: jquery("." + opts.names._codetxt).val() },
            success: callback
        });

    },
    //when code textbox value changed, trigger this event
    _codechangeevent = function (opts) {
        //if codetext onchange trigger 
        opts.onkeydown(jquery("." + opts.names._codetxt).val());
        //------------------import---------------------------
        if (opts.onlykeyboard)
            currentobj.val(jquery("." + opts.names._codetxt).val());
        else {
            jquery("." + opts.names._resultsselect).empty();
            //get data from server
            _getdata(opts, function (data) {
                var data = eval("(" + data + ")");
                jquery(data).each(function (index, element) {
                    if (element.name != undefined)
                        jquery("." + opts.names._resultsselect).append("<option value='" + element.name + "'>" + element.name + "</option>");
                });
            });
        }

    },
    //letter button event
    _letterevent = function (opts) {
        jquery("." + opts.names._letterbtn).bind("click",
            function () {
                if (opts.maxlength == null) {
                    jquery("." + opts.names._codetxt).val(jquery("." + opts.names._codetxt).val() + jquery(this).val());
                    _codechangeevent(opts);
                }
                else if (opts.maxlength != null && jquery("." + opts.names._codetxt).val().length < opts.maxlength) {
                    jquery("." + opts.names._codetxt).val(jquery("." + opts.names._codetxt).val() + jquery(this).val());
                    _codechangeevent(opts);
                }
            });
        //clear button binding event.
        jquery("." + opts.names._clearbtn).bind("click", function () {
            jquery("." + opts.names._codetxt).val("");
            if (currentobj != null) currentobj.val("");
        });
    },
    //delete button click trigger
    _deleteevent = function (opts) {
        jquery("." + opts.names._delbtn).bind("mousedown", function () {
            var val = jquery("." + opts.names._codetxt).val();
            if (val.length != 0) {
                val = val.substring(0, val.length - 1);
                jquery("." + opts.names._codetxt).val(val);
                _codechangeevent(opts);
            }
        });
    },
    //query button click
    _queryevent = function (opts) {
        // _getdata(opts, filldata);
    },
    //when click select item
    _selectclickevent = function (opts) {
        jquery("." + opts.names._resultsselect).bind("click",
        function () {
            if (currentobj != null) currentobj.val(jquery("." + opts.names._resultsselect).val());
        });
    },
    //add class attribute to element
    _addclstoele = function (cls, ele) {
        if (cls != undefined)
            ele.addClass(cls);
    },
    //create input control element
    _createinputelement = function (type, cls, val) {
        var element = jquery("<input type='" + type + "' />");
        _addclstoele(cls, element);
        if (val != undefined)
            element.val(val);
        return element;
    },
    //create div element
    _createdivelement = function (cls) {
        var element = jquery("<div />");
        _addclstoele(cls, element);
        return element;
    },
    //create keyboard button
    _createkeyboard = function (container, opts) {
        var i = 0;
        //create 0-9 number
        for (i = 0; i < 10; i++) {
            container.append(_createinputelement("button", opts.names._letterbtn, i));
        }
        //create a-z word
        for (i = 97; i < 123; i++) {
            container.append(_createinputelement("button", opts.names._letterbtn, String.fromCharCode(i)));
        }
        //create A-Z word
        if (!opts.simplekeyboard) {
            for (i = 65; i < 91; i++) {
                container.append(_createinputelement("button", opts.names._letterbtn, String.fromCharCode(i)));
            }
        }
    },
    //button bind  event
    _attachevent = function (opts) {
        _letterevent(opts);

    },
    //restore keyboard 
    _restorekeyboard = function (opts) {
        jquery("." + opts.names._codetxt).val("");
        jquery("." + opts.names._resultsselect).empty();
    },
    //toggle visible
    _visiblekeyboard = function (v, opts) {
        if (v) {

            jquery("." + opts.names._maindiv).css("left", currentobj.offset().left);
            jquery("." + opts.names._maindiv).css("top", currentobj.offset().top + currentobj.outerHeight());
            jquery("." + opts.names._maindiv).show();
            _restorekeyboard(opts);
        }
        else {
            jquery("." + opts.names._maindiv).hide();
            _restorekeyboard(opts);
        }
    },
    //Init face
    _showkeyboard = function (opts) {
        //get main content
        // var content = jquery("."+opts.names._maindiv).hide();
        var content = _createdivelement(opts.names._maindiv).css("position", "absolute").css("z-index", "9999").hide();
        //create keyboard left panel
        var skbleft = _createdivelement(opts.names._leftdiv)
            .append(_createinputelement("text", opts.names._codetxt))
        skbleft.append(jquery("<select />").addClass(opts.names._resultsselect).attr("multiple", opts.listmultiple));

        //create keyboard right panel
        var skbright = _createdivelement(opts.names._rightdiv);

        //view or noview
        skbleft = jquery(skbleft).css("display", opts.onlykeyboard == true ? "none" : "");
        if (opts.onlykeyboard) skbright.css("float", "left");

        //create keyboard toolbar of right panel
        var skboperation = _createdivelement(opts.names._operationdiv)
            .append(_createinputelement("button", opts.names._delbtn, opts.names._delbtnviewname))
            .append(_createinputelement("button", opts.names._clearbtn, opts.names._clearbtnviewname))
            
            .append(_createinputelement("button", opts.names._closebtn, opts.names._closebtnviewname).bind("click",
            function () {
                _visiblekeyboard(false, opts);
            }));
        if (!opts.onlykeyboard) {
            skboperation.append(_createinputelement("button", opts.names._querybtn, opts.names._querybtnviewname));
        }
        //create keyboard
        var skbkeyboard = _createdivelement(opts.names._keyboarddiv);
        _createkeyboard(skbkeyboard, opts);
        //attatch toobar to right panel
        skbright.append(skboperation)
                    .append(skbkeyboard);

        //attatch soft keyboard to HTML
        content.append(skbleft);
        content.append(skbright);
        jquery("body").append(content);

        //binding event
        _attachevent(opts);
        _selectclickevent(opts);
        _deleteevent(opts);
    };
    //start pulgin
    jquery.fn.softkeyboard = function (options) {
        //merge parameters to opts
        var opts = jquery.extend({}, jquery.fn.softkeyboard.defaults, options);
        //Init keyboard to HTML page
        _showkeyboard(opts);
        //bind event to current element
        this.each(function () {
            jquery(this).bind("click", function () {
                currentobj = jquery(this); //get current click object. --new
                _visiblekeyboard(true, opts);
            });
        });

    };
    //default parameters
    jquery.fn.softkeyboard.defaults = {
        names: {
            _delbtn: "skbdel",
            _clearbtn: "skbclear",
            _querybtn: "skbquery",
            _closebtn: "skbclose",
            _letterbtn: "skbbtn",
            _maindiv: "skbsoftkeyboard",
            _leftdiv: "skbleft",
            _rightdiv: "skbright",
            _keyboarddiv: "skbkeyboard",
            _operationdiv: "skboperation",
            _codetxt: "skbcode",
            _resultsselect: "skbresults",
            _postparamcode: "sfbcode",
            _clearbtnviewname: "清除",
            _delbtnviewname: "删除",
            _querybtnviewname: "查询",
            _closebtnviewname: "关闭"
        },
        listmultiple: true, //keyboard results list is multiple? ture is multiple ,false is list
        simplekeyboard: true, //simple keyboard dont create A-z letter only create 0-9,a-z 
        animation: false, //Animation effects for visible keyboard panel
        onlykeyboard: false,
        maxlength: null, //keyboard textbox allowed maximum length 
        requestdataurl: null,
        oncompleted: function (data) { }, //When completed softkeyboard operation trigger the events
        onkeydown: function (data) { } //when  keydown(textbox change) trigger the events

    };


})(jQuery);